package ${initProjectVo.packageNameValue}.core.interceptor;


import com.auth0.jwt.interfaces.DecodedJWT;
import ${initProjectVo.packageNameValue}.common.jwt.JWTUtils;
import ${initProjectVo.packageNameValue}.core.annotation.JwtIgnore;
import ${initProjectVo.packageNameValue}.core.exception.AccessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Faye.Wang
* @version 1.0
* @date 2020/9/4 16:22
* @Description 访问token验证，接口调用token访问
*/
public class AccessServerInterceptor extends HandlerInterceptorAdapter {

private static Logger logger = LoggerFactory.getLogger(AccessServerInterceptor.class);

@Value("${"$"}{jwt.access.token.secret}")
private String jwtAccessSecret;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if(handler instanceof HandlerMethod){
        HandlerMethod handlerMethod =(HandlerMethod)handler;
        JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
        if(jwtIgnore!=null){
            return true;
        }
    }

    String accessToken = request.getHeader(JWTUtils.AUTH_HEADER_KEY);

        System.out.println(accessToken);

        if(StringUtils.isBlank(accessToken)){
            logger.info("## authHeader ERROR= {}", "非法请求");
            throw new AccessException("非法请求");
        }
        DecodedJWT jwt = JWTUtils.verify(accessToken);
        if(org.springframework.util.StringUtils.isEmpty(jwt)){
            logger.info("## authHeader ERROR= {}", "非法请求");
            throw new AccessException("非法请求");
        }

        return true;
    }
}
